<template>
    <div class="movie-page">
        <h1 class="page-title">电影列表</h1>
        <div class="search-container">
            <input type="text" v-model="searchKeyword" placeholder="搜索电影标题、描述或演员">
        </div>
        <div v-if="isLogin" class="movie-form-container">
            <form class="movie-form">
                <div class="form-group">
                    <label for="movie-title">电影标题</label>
                    <input type="text" id="movie-title" v-model="title" placeholder="请输入电影标题" />
                </div>
                <div class="form-group">
                    <label for="movie-desc">电影描述</label>
                    <input type="text" id="movie-desc" v-model="desc" placeholder="请输入电影描述" />
                </div>
                <div class="form-group">
                    <label for="movie-actors">演员列表</label>
                    <input type="text" id="movie-actors" v-model="actors" placeholder="请输入演员列表" />
                </div>
                <div class="form-group">
                    <label for="movie-picPaths">剧照</label>
                    <input 
                        type="text" 
                        id="movie-picPaths" 
                        v-model="picPaths" 
                        placeholder="请输入剧照链接" 
                        @input="updatePreview"
                        @blur="validateImageUrl"
                    />
                    <div class="preview-container" v-if="picPaths">
                        <div v-if="isValidImageUrl(picPaths)">
                            <img 
                                :src="picPaths" 
                                alt="预览图" 
                                class="preview-image" 
                                @error="handleImageError"
                                @load="onImageLoaded"
                                @loadstart="onImageLoadStart"
                            />
                            <p v-if="!imageLoaded" class="loading-text">加载中...</p>
                        </div>
                        <p v-else class="invalid-url">请输入有效的图片URL (以http/https开头)</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="movie-playUrl">播放地址</label>
                    <input type="text" id="movie-playUrl" v-model="playUrl" placeholder="请输入播放地址" />
                </div>
                <button type="button" class="submit-button" @click="addMovie">提交</button>
            </form>
        </div>
        <hr class="divider" />
        <div class="movie-list">
            <router-link :to="{ name: 'moviedetail', query: { id: movie.id } }" 
                         class="movie-link" 
                         v-for="movie in filteredMovies" 
                         :key="movie.id">
                <div class="movie-item">
                    <h2 class="movie-title">{{ movie.title }}</h2>
                    <p class="movie-meta">
                        上架时间: {{ movie.addedTime || '未知' }} | 主演: {{ movie.actors }}
                        <hr>
                        <span class="multi-line-ellipsis">电影描述: {{ movie.desc }}</span>
                        <hr>
                        <!-- 移除 single-line-ellipsis 类，确保图片完整显示 -->
                        <span>剧照: 
                            <img 
                                :src="movie.picPaths" 
                                alt="剧照" 
                                class="movie-poster" 
                                @error="handleMovieImageError"
                                @load="onImageLoaded"
                                @loadstart="onImageLoadStart"
                            />
                        </span>
                        <hr>
                        <span class="single-line-ellipsis">播放地址: <a :href="movie.playUrl" target="_blank">{{ movie.playUrl }}</a></span>
                        <hr>
                        上传用户id: {{ movie.userid }}
                    </p>
                    <button type="button" class="delete-button" @click="deleteMovieById(movie.id)">删除</button>
                </div>
            </router-link>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { getList, add, deleteMovie } from '../utils/request';
import { useUserStore } from '../stores/user';
import { ElMessageBox } from 'element-plus';
import { TableName } from '../utils/request';

const userStore = useUserStore();
const isLogin = ref(userStore.isAuthenticated);
const user = ref(userStore.getUser);

const title = ref('');
const desc = ref('');
const actors = ref('');
const picPaths = ref('');
const playUrl = ref('');
const imageLoaded = ref(false);
const imageError = ref(false);
const searchKeyword = ref('');
const movies = ref<any[]>([]);
const isLoading = ref(true);

// 检查URL是否为有效的图片URL
const isValidImageUrl = (url: string) => {
  return url.startsWith('http://') || url.startsWith('https://');
};

// 更新图片预览
const updatePreview = () => {
  imageLoaded.value = false;
  imageError.value = false;
};

// 验证图片URL
const validateImageUrl = () => {
  if (picPaths.value && !isValidImageUrl(picPaths.value)) {
    ElMessageBox.alert('请输入有效的图片URL (以http/https开头)', '提示');
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  console.error('图片加载失败:', (event.target as HTMLImageElement).src);
  (event.target as HTMLImageElement).src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="200"><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="red">图片加载失败</text></svg>';
  imageError.value = true;
};

// 处理电影列表中剧照图片加载错误
const handleMovieImageError = (event: Event) => {
  console.error('电影列表图片加载失败:', (event.target as HTMLImageElement).src);
  (event.target as HTMLImageElement).src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="200"><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="red">图片加载失败</text></svg>';
};

// 图片开始加载
const onImageLoadStart = (event: Event) => {
  console.log('图片开始加载:', (event.target as HTMLImageElement).src);
};

// 图片加载完成
const onImageLoaded = () => {
  imageLoaded.value = true;
};

const addMovie = async () => {
    if (user.value && user.value.id) {
        if (!title.value || !desc.value) {
            ElMessageBox.alert('标题和描述不能为空', '提示');
            return;
        }
        if (picPaths.value && !isValidImageUrl(picPaths.value)) {
            ElMessageBox.alert('请输入有效的剧照URL', '提示');
            return;
        }
        const newMovie = {
            title: title.value,
            desc: desc.value,
            actors: actors.value,
            picPaths: picPaths.value,
            playUrl: playUrl.value,
            userid: user.value.id,
            typeIndex: TableName.Movies
        };
        const r = await add(newMovie);
        if (r) {
            try {
                const data = await getList(TableName.Movies);
                console.log('获取到的新电影列表:', data);
                if (data) {
                    movies.value = data;
                    title.value = '';
                    desc.value = '';
                    actors.value = '';
                    picPaths.value = '';
                    playUrl.value = '';
                    imageLoaded.value = false;
                    imageError.value = false;
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
            } catch (error) {
                console.error('重新获取电影列表失败:', error);
            }
        }
    } else {
        ElMessageBox.alert('请先登录', '提示');
    }
};

onMounted(async () => {
    try {
        const data = await getList(TableName.Movies);
        movies.value = data;
    } catch (error) {
        console.error('获取电影列表失败:', error);
    } finally {
        isLoading.value = false;
    }
});

const deleteMovieById = async (id: number) => {
    const confirm = await ElMessageBox.confirm('确定要删除这部电影吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    });
    if (confirm === 'confirm') {
        const success = await deleteMovie(id, TableName.Movies);
        if (success) {
            try {
                const data = await getList(TableName.Movies);
                movies.value = data;
                ElMessageBox.alert('删除成功', '提示');
            } catch (error) {
                console.error('重新获取电影列表失败:', error);
            }
        } else {
            ElMessageBox.alert('删除失败', '提示');
        }
    }
};

const filteredMovies = computed(() => {
    const keyword = searchKeyword.value.toLowerCase();
    const filtered = movies.value.filter(movie => {
        return (
            movie.title?.toLowerCase().includes(keyword) ||
            movie.desc?.toLowerCase().includes(keyword) ||
            movie.actors?.toLowerCase().includes(keyword)
        );
    });

    const userId = user.value?.id;

    if (userId) {
        return filtered.sort((a, b) => {
            const aMatch = a.userid === userId;
            const bMatch = b.userid === userId;

            if (aMatch && !bMatch) return -1;
            if (!aMatch && bMatch) return 1;
            return 0;
        });
    }

    return filtered;
});
</script>

<style scoped>
.movie-page {
    width: 100%;
    margin: 0 auto;
    padding: 20px;
    margin-top: -70px;
}

.page-title {
    font-size: 32px;
    text-align: center;
    margin-bottom: 20px;
}

.search-container {
    margin-bottom: 20px;
}

.search-container input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.movie-form-container {
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.movie-form {
    display: flex;
    flex-direction: column;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
}

.form-group input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.submit-button {
    background-color: #28a745;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.submit-button:hover {
    background-color: #218838;
}

.divider {
    border: none;
    border-top: 1px solid #e0e0e0;
    margin: 20px 0;
}

.movie-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.movie-item {
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    transition: box-shadow 0.3s;
}

.movie-item:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.movie-link {
    text-decoration: none;
    color: #333;
}

.movie-title {
    font-size: 20px;
    margin-bottom: 10px;
}

.movie-meta {
    font-size: 14px;
    color: #666;
}

hr {
    border: 1px dashed;
    width: 100%;
    margin: 10px 0;
}

.multi-line-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 6;
    overflow: hidden;
    text-overflow: ellipsis;
}

.delete-button {
    background-color: #dc3545;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
    margin-top: 10px;
}

.delete-button:hover {
    background-color: #c82333;
}

.preview-container {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: #f9f9f9;
}

.preview-image, .movie-poster {
    width: 150px;
    height: auto;
    border-radius: 4px;
    transition: opacity 0.3s;
}

.invalid-url {
    color: #dc3545;
    margin: 0;
}

.loading-text {
    color: #666;
    font-size: 14px;
    text-align: center;
    margin-top: 5px;
}
</style>